<?php

namespace app\common\model;

use app\admin\model\Admin;
use app\common\controller\Queue;
use app\common\service\PromotionServer;
use think\Db;
use think\Exception;
use think\Model;


class AgentOrder extends Model
{

    

    

    // 表名
    protected $name = 'agent_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'status_text',
	    'level_text'
    ];
	
	
	const STATUS_WAIT = 0;
	const STATUS_Y = 1;
	
	public static $statusList = [
		self::STATUS_Y => '已支付',
		self::STATUS_WAIT => '待支付',
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}
	
	
	public function getLevelTextAttr($value, $data) {
		$value = $value ? : $data['level'];
		$list = \app\admin\model\User::$levelList;
		return $list[$value] ??'';
	}
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function recommend() {
		return $this->belongsTo('user', 'recommend_user_id', 'id', '', 'left')->setEagerlyType(0);
	}
		
		/**
	 * 支付成功
	 * @param $orderId 订单ID
	 * @param $transactionNo 支付流水号
	 * @return bool|false|int
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function paySuccess($orderId, $transactionNo) {
		$order = $this->find($orderId);
		if(!$order) {
			$this->error = '没有相关订单';
			return false;
		}
		
		if($order['status'] == self::STATUS_Y) {
			return true;
		}
		
		
		$this->startTrans();
		try {
			$res = $this->save(['status' => self::STATUS_Y, 'transaction_no' => $transactionNo], ['id' => $orderId]);
			if(!$res) {
				throw new Exception('更改订单状态出错');
			}
			if($order['level'] == \app\admin\model\User::LEVEL_PROMOTION) {
				
				$user = User::get($order['user_id']);
				$data = [
					'level' => \app\admin\model\User::LEVEL_PROMOTION,
					'recommend_user_id' => $user['recommend_user_id'] ? : $order['recommend_user_id']
				];
				
				
				$userRes = Db::name('user')
					->where(['id' => $order['user_id']])
					->update($data);
				
				if(!$userRes) {
					throw new Exception("更改代言人等级出错");
				}
				
				$user['recommend_user_id'] = $data['recommend_user_id'];
				$servierObj = new PromotionServer();
				//填写资料
				$infoRes =  $servierObj->createInfo($user);
				if(!$infoRes['status']) {
					throw new Exception('添加代言人资料出错');
				}
				
				//生成赠送的订单
				$setting = Db::name('setting')->find();
				if($setting && $setting['promotion_join_number'] > 0) {
					$goodsId = $setting['reward_goods_id'];
					$specId = $setting['reward_spec_id'];
					
					if($user['area'] == \app\admin\model\User::AREA_SZ) {
						$rule = Db::name('ruleSz')->find();
						$goodsId = $rule['reward_goods_id'];
						$specId = $rule['reward_spec_id'];
					}
					$orderModel = new Order();
					$orderRes = $orderModel->addRewardOrder($order['user_id'], $setting['promotion_join_number'], $goodsId, $specId, $orderModel::TYPE_GIFT,$user['area'], '开通代言人赠送订单', $user['recommend_user_id'], $order['amount']);
					if(!$orderRes) {
						throw new Exception('添加订单出错');
					}
				}
				
//				//深圳的推荐人获得10%佣金到余额
//				if($user['area'] == \app\admin\model\User::AREA_SZ && $user['recommend_user_id']) {
//					$recommendUser = \app\admin\model\User::get($user['recommend_user_id']);
//					$commission = $order['amount'] * 0.1;
//					if($commission > 0 && $recommendUser['level'] > \app\admin\model\User::LEVEL_USER) {
//						$commissionModel = new Commission();
//						$commissionRes = $commissionModel->rebate($user['recommend_user_id'], $order['user_id'], $orderId, 0, 0, $commission, '推荐代言人佣金', $commissionModel::TYPE_RECOMMEND);
//						if(!$commissionRes) {
//							throw new Exception('添加推荐人佣金出错');
//						}
//					}
//				}
				
			} else {
				$userRes = Db::name('user')
					->where(['id' => $order['user_id']])
					->update(['level' => \app\admin\model\User::LEVEL_WAREHOUSE]);

				if(!$userRes) {
					throw new Exception("更改提货点等级出错");
				}
				
				$shopRes = Db::name('agentShop')->where(['user_id' => $order['user_id']])
					->update(['status' => 1]);
				if($shopRes === false) {
					throw new Exception('更改资料状态出错');
				}
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
		
		
	}
	
	

}
